package com.xdl.modules.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beluga.core.util.Func;
import com.beluga.core.util.SnowflakeIdUtil;
import com.xdl.common.jwt.JWTHelper;
import com.xdl.common.jwt.JWTInfo;
import com.xdl.modules.dto.UserDto;
import com.xdl.modules.dto.WechatLoginDto;
import com.xdl.modules.dto.WechatUserDto;
import com.xdl.modules.entity.WxUser;
import com.xdl.modules.mapper.WxUserMapper;
import com.xdl.modules.service.WxUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 微信用户表 服务实现类
 * </p>
 *
 * @author iron guo
 * @since 2022-04-21
 */
@Slf4j
@Service
@AllArgsConstructor
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements WxUserService {

    private WxMaService wxMaService;

    @Override
    public WechatUserDto loginWithWechat(WechatLoginDto user) throws Exception{
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(user.getCode());
        QueryWrapper<WxUser> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(WxUser::getOpenId,sessionInfo.getOpenid());
        WxUser wechatUser = this.baseMapper.selectOne(wrapper);
        if(Func.isEmpty(wechatUser)){
            //TODO save wechat info to datsource
            WxUser wxuser=new WxUser();
            wxuser.setHeadImgUrl(user.getHeadImgUrl());
            wxuser.setNickname(user.getNickname());
            wxuser.setOpenId(sessionInfo.getOpenid());
            //生成唯一会员号 支持后期自行修改只有一次机会
            wxuser.setUserName("xdl_"+ SnowflakeIdUtil.nextId());
            this.baseMapper.insert(wxuser);
            Func.copy(wxuser,wechatUser);
        }
        UserDto dto=new UserDto();
        Func.copy(wechatUser,dto);
        String token = JWTHelper.generateToken(JWTInfo.builder().userName(wechatUser.getUserName()).userId(String.valueOf(wechatUser.getId())).openId(sessionInfo.getOpenid()).build(), 90);
        return new WechatUserDto().setToken(token).setUserinfo(dto);
    }
}
